package com.sky.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.service.ShoppingCartService;
import com.sky.service.WebSocketServer;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分类业务层
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private WebSocketServer webSocketServer;
    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;

    /**
     * C端- 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {//TODO
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
       // User user = userMapper.getById(userId);
        String orderNumber = ordersPaymentDTO.getOrderNumber();
        Orders orders = orderMapper.getByNumberAndUserId(orderNumber, userId);
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orderMapper.update(orders);
        //TODO
        /*//调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );*/

        /*if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));*/
        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(orderNumber, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        /*Orders orders1 = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();*/

      //  orderMapper.update(orders);

//推送消息
        Map map = new HashMap<>();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","订单号"+orderNumber);
        //通过websocket实现来单提醒,向客户单浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        return new OrderPaymentVO();
    }


    /**
     * 检查客户的收货地址是否超出配送范围
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("adress",shopAddress);
        map.put("output","json");
        map.put("ak",ak);
        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if (!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺金纬度坐标
        String shopLngLat = lat+","+lng;
        map.put("address",address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
         jsonObject = JSON.parseObject(userCoordinate);
         if (!jsonObject.getString("status").equals("0")){
             throw new OrderBusinessException("收货地址解析失败");
         }

         //数据解析
        location=jsonObject.getJSONObject("result").getJSONObject("location");
         lat=location.getString("lat");
         lng=location.getString("lng");
         //用户收货地址经纬度坐标
        String userLngLat = lat+","+lng;
        map.put("oridin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");
        if (distance>5000){
            throw new OrderBusinessException("超出配送范围");
        }

    }




    /**
     *  C端-支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    @ApiOperation("支付成功，修改订单状态")
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

//推送消息
        Map map = new HashMap<>();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","订单号"+outTradeNo);
        //通过websocket实现来单提醒,向客户单浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }


    /**
     *  C端-用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @ApiOperation("提交订单")
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        AddressBook addressBook = addressBookMapper.selectById(ordersSubmitDTO.getAddressBookId());
        //判断是否有收货地址
        if (addressBook == null) {
            //如果没有就抛出一个异常
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //TODO 查用户的收货地址是否超出配送范围
       // checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        //如果有获取用户id
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        //查询当前用户的购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //构造订单数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setUserId(userId);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setOrderTime(LocalDateTime.now());

        //向订单表插入1条数据
        orderMapper.insert(orders);
        //订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        //向明细表里插入n条数据
        orderDetailMapper.insertBatch(orderDetailList);
        //清理购物车数据
        shoppingCartMapper.delete(userId);
        //封装结果并返回
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();

        return orderSubmitVO;
    }

    /**
     *  C端-查询历史订单
     *
     * @param
     * @return
     */
    @Override
    public Page<OrderVO> page(Integer page, Integer pageSize, Integer status) {
        PageHelper.startPage(page, pageSize);
        Page<OrderVO> pages = orderMapper.getByStatus(status, BaseContext.getCurrentId());
        for (OrderVO vo : pages) {
            List<OrderDetail> orderDetailList = orderDetailMapper.getByUserId(vo.getId());
            vo.setOrderDetailList(orderDetailList);
        }

        return pages;
    }

    /**
     *  C端-查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO getById(Long id) {
        List<OrderDetail> orderDetail = orderDetailMapper.getByUserId(id);
        OrderVO orders = orderMapper.getById(id);
        AddressBook addressBook = addressBookMapper.selectById(orders.getAddressBookId());
        orders.setAddressBookId(addressBook.getId());
        orders.setAddress(addressBook.getCityName() + addressBook.getProvinceName() + addressBook.getDistrictName());
        orders.setOrderDetailList(orderDetail);
        return orders;
    }

    /**
     *  C端-取消订单
     *
     * @param id
     */
    @Override
    public void cancelById(Long id) {

        orderMapper.updateStatusById(id,Orders.CANCELLED);


    }

    /**
     * C端-再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        List<OrderDetail> orderDetails = orderMapper.getId(id);

        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCartDTO shoppingCartDTO = new ShoppingCartDTO();
            shoppingCartDTO.setDishId(orderDetail.getDishId());
            shoppingCartDTO.setSetmealId(orderDetail.getSetmealId());
            shoppingCartService.addShoppingCart(shoppingCartDTO);
        }

    }

    /**
     * B端-订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public Page<OrderVO> pageAll(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<OrderVO> pages = orderMapper.getAll(ordersPageQueryDTO);
        for (OrderVO vo : pages) {
            List<OrderDetail> orderDetailList = orderDetailMapper.getByUserId(vo.getId());
            vo.setOrderDetailList(orderDetailList);
        }

        return pages;
    }

    /**
     * B端-查询各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        Integer confirmed  =orderMapper.statistics(Orders.CONFIRMED);//3,待派送
        Integer deliveryInProgress =orderMapper.statistics(Orders.DELIVERY_IN_PROGRESS);//4,派送中
        Integer toBeConfirmed  =orderMapper.statistics(Orders.TO_BE_CONFIRMED);//2,待接单
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * B端-完成订单
     * @param id
     */
    @Override
    public void completeById(Long id) {
        orderMapper.updateStatusById(id,Orders.COMPLETED);//5已完成
    }

    /**
     * B端-取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);//设置状态6,已取消
        orders.setCancelReason(ordersCancelDTO.getCancelReason());//设置取消的原因
        orderMapper.update(orders);
    }

    /**
     * B端-接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        orderMapper.updateStatusById(ordersConfirmDTO.getId(),Orders.CONFIRMED);//设置状态3,已接单
    }

    /**
     * B端-拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void reiection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = new Orders();
        orders.setId(ordersRejectionDTO.getId());
        orders.setStatus(Orders.CANCELLED);//设置状态6,已取消
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());//设置拒绝的理由
        orderMapper.update(orders);
    }

    /**
     * 派送定单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        orderMapper.updateStatusById(id,Orders.DELIVERY_IN_PROGRESS);//设置状态4,派送中
    }

    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        OrderVO byId = orderMapper.getById(id);
        if (byId==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND)
                    ;
        }
        //基于WebSocket实现催单
        Map map = new HashMap<>();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号:" + byId.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

    }


}
